package com.rwx.service;

import com.rwx.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SpringSecurityUserService implements UserDetailsService {
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    //模拟数据库中的用户数据
    public Map<String, User> map = new HashMap<>();

    private void init(){
        User user1 = new User();
        user1.setUsername("admin");
        user1.setPassword(passwordEncoder.encode("admin"));

        User user2 = new User();
        user2.setUsername("xiaoming");
        user2.setPassword(passwordEncoder.encode("1234"));

        map.put(user1.getUsername(),user1);
        map.put(user2.getUsername(),user2);
    }



    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        init();
        System.out.println("用户输入名为："+username);
        User userInDb = map.get(username);
        if(userInDb == null){
            //根据用户名没有查询到用户
            return null;
        }else{
            List<GrantedAuthority> list = new ArrayList<>();

            list.add(new SimpleGrantedAuthority("delete"));
            if(username.equals("admin")){
                list.add(new SimpleGrantedAuthority("add"));
                list.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
            }

            //String passwordInDb = "{noop}" + userInDb.getPassword();
            String passwordInDb = userInDb.getPassword();

            org.springframework.security.core.userdetails.User securityUser = new org.springframework.security.core.userdetails.User(username,passwordInDb,list);
            return securityUser;
        }
//
//


    }
}
